import { reqLogin, reqLoginout } from "../../api/user";


const state = {
  userInfo: null,
  isLogin: false,
  cookie: null,
  loginDialogVisible: false, // 登录弹窗显示与隐藏
};

const getters = {
  isLogin(state) {
    return (
      state.isLogin || JSON.parse(window.sessionStorage.getItem("isLogin"))
    );
  },
  userInfo(state) {
    return (
      state.userInfo || JSON.parse(window.sessionStorage.getItem("userInfo"))
    );
  },
  cookie(state) {
    return state.cookie || window.sessionStorage.getItem("cookie");
  },
};
const actions = {
  // 登入
  loginAction({ commit }, { phone, password }) {
    return new Promise((resolve, reject) => {
      reqLogin({ phone, password })
        .then((res) => {
          commit("LOGIN", res);
          window.sessionStorage.setItem("token", res.token);
          window.sessionStorage.setItem("cookie", res.cookie);
          window.sessionStorage.setItem("isLogin", true);
          window.sessionStorage.setItem(
            "userInfo",
            JSON.stringify(res.profile)
          );
          resolve(res);
        })
        .catch((res) => {
          reject(res);
        });
    });
  },
  // 登出
  loginOut({ commit }) {
    return new Promise((resolve, reject) => {
      reqLoginout()
        .then((res) => {
          window.sessionStorage.removeItem("token");
          window.sessionStorage.removeItem("cookie");
          window.sessionStorage.removeItem("isLogin");
          window.sessionStorage.removeItem("userInfo");
          commit("LOGINOUT");
          resolve(res);
        })
        .catch((res) => {
          reject(res);
        });
    });
  },
};
const mutations = {
  LOGIN(state, res) {
    state.isLogin = true;
    state.userInfo = res.profile;
    state.cookie = res.cookie;
  },
  LOGINOUT(state) {
    state.isLogin = false;
    state.userInfo = null;
  },
  setLoginDialog (state, val = null) {
    state.loginDialogVisible = val
  },
};
export default {
  state,
  getters,
  actions,
  mutations,
};
